package com.oraro.paygatewaybiz.exception;

import com.github.wxpay.sdk.WXPayUtil;
import com.oraro.common.result.Result;
import com.oraro.middleservice.logger.starter.supports.BizLoggerHelper;
import com.oraro.paygatewaybiz.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: jianghuiyong
 * @Date: 2018/11/26 19:12
 * @Version 1.0
 */
@RestControllerAdvice
@Slf4j
public class RRExceptionHandler {

    @Autowired
    private BizLoggerHelper bizLoggerHelper;

    @ExceptionHandler(RRException.class)
    public Result handleRRException (RRException e) {
        log.error(e.toString());
        return Result.error(e.getCode(), e.getMsg());
    }

    @ExceptionHandler(AliNotifyException.class)
    public String handleAliNotifyException(AliNotifyException e) {
        log.error(e.getMsg());
        bizLoggerHelper.log(e.getMsg());
        return Constants.RETURN_ALIPAY_VALUE_FAIL;
    }

    @ExceptionHandler(WXNotifyException.class)
    public String handleWXPayException (WXNotifyException e) {
        log.error(e.getMsg());
        bizLoggerHelper.log(e.getMsg());
        Map<String, String> returnData = new HashMap<>();
        returnData.put("return_code", "FAIL");
        returnData.put("return_msg", e.getMsg());
        String xmlResult = "";
        try {
            xmlResult = WXPayUtil.mapToXml(returnData);
        } catch (Exception ex) {
            log.error(ex.toString());
        }
        return xmlResult;
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e){

        BindingResult bindingResult = e.getBindingResult();
        return Result.error(bindingResult.getFieldError().getDefaultMessage());
    }

    @ExceptionHandler(Exception.class)
    public Result handleException (Exception e) {
        log.error(e.toString());
        return Result.error(e.getMessage());
    }

}
